package com.tanhua.app.service;

import com.tanhua.api.service.UserInfoApi;
import com.tanhua.app.exception.BusinessException;
import com.tanhua.autoconfig.template.AipTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.model.pojo.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipTemplate aipTemplate;

    /**
     * 保存用户详细信息
     * @param userInfo
     */
    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    /**
     * 根据主键更新头像
     * @param headPhoto
     * @param userInfo
     */
    public void updateHead(MultipartFile headPhoto, UserInfo userInfo) throws IOException {

        // 1. 将图片保存到oss文件存储上
        String imagerUrl = ossTemplate.upload(headPhoto.getOriginalFilename(),
                headPhoto.getInputStream());

        // 2. 使用aip校验图片是否正确
        boolean detect = aipTemplate.detect(imagerUrl);

        // 2.1 不正确，抛出异常
        if (!detect) {
            throw new BusinessException(ErrorResult.faceError());
        }

        // 2.2 正确，将数据更新到数据库中
        userInfo.setAvatar(imagerUrl);
        userInfoApi.updateById(userInfo);

    }

    // 根据主键查询数据
    public UserInfoVo findById(Long userID) {
        UserInfo userInfo = userInfoApi.findById(userID);
        // 页面需要的数据不一样，分装新的数据
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);

        if (userInfo.getAge() != null) {
            userInfoVo.setAge(userInfo.getAge().toString());
        }

        return userInfoVo;
    }


    /**
     * 根据主键更新信息
     * @param userInfo
     */
    public void updateById(UserInfo userInfo) {
        userInfoApi.updateById(userInfo);
    }
}
